const { parseRule } = require('./parser')
const cheerio = require('cheerio')
const _ = require('lodash')
const request = require('./request')

function parseChapter (source, doc) {
  const $ = cheerio.load(doc)

  const list = parseRule(source.ruleChapterList, $)

  const chapterMap = {
    chapterName: 'ruleChapterName',
    contentUrl: 'ruleContentUrl'
    // ruleBookContent: 'ruleBookContent'
  }

  const chapterItems = []

  list.each(function () {
    const item = {}
    Object.keys(chapterMap).forEach(prop => {
      item[prop] = _.trim(parseRule(source[chapterMap[prop]], $(this)))
    })
    if (item.chapterName) {
      chapterItems.push(item)
    }
  })

  return chapterItems
}

async function downloadChapter (source, url) {
  if (!_.startsWith(url, 'http')) {
    url = source.bookSourceUrl + url
  }
  return request.get(url)
}

async function chapter (source, url) {
  const doc = await downloadChapter(source, url)
  return parseChapter(source, doc)
}

module.exports = {
  parseChapter,
  downloadChapter,
  chapter
}
